package com.mutouren.modules.datapush.local;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import com.alibaba.fastjson.JSON;
import com.mutouren.common.utils.HttpClientUtils;
import com.mutouren.common.utils.HttpResult;
import com.mutouren.modules.datapush.base.Constant;
import com.mutouren.modules.datapush.base.PushMessage;
import com.mutouren.modules.datapush.base.PushStatus;
import com.mutouren.modules.datapush.server.AbstractServer;
import com.mutouren.modules.datapush.strategy.ConcurrentStrategy;
import com.mutouren.modules.datapush.strategy.RepeatStrategy;

public class HttpServerProxy extends AbstractServer{
	
	private final static String proxyMethodAlias = Constant.defaultMethodAlias;
	private final static int maxThreadSize = 3;
	private final String url;
	private PoolingHttpClientConnectionManager connection = HttpClientUtils.createConnectionManager(maxThreadSize, maxThreadSize);

	public HttpServerProxy(String serverAlias, String url) {
		super(serverAlias, maxThreadSize);
		if (StringUtils.isBlank(url)) {
			throw new RuntimeException("url is blank");
		}			
		this.url = url.trim();
		init();
	}
	
	private void init() {
		repeatStrategyManager.addRepeatStrategy(new RepeatStrategy(
				proxyMethodAlias, 2, 8, 
				20, 2, "ok"));		
	}
	
	protected void send(PushMessage message) {
		
		message.setRequestCount(message.getRequestCount() + 1);
		message.setLastUpdateTime(new Date());
				
		//HttpClientUtils httpClient = new HttpClientUtils(message.getRealUrl(), message.getMethodType().name);
		//HttpClientUtils httpClient = new HttpClientUtils(this.url);
		HttpClientUtils httpClient = new HttpClientUtils(this.url, "post", connection);
		
		try {
//			if ((message.getMethodType() == MethodType.POST)&&(!StringUtils.isBlank(message.getRequestBody()))) {
//				httpClient.setBody(message.getRequestBody(), message.getCharset().name, message.getContentType().name);
//			}
			httpClient.setByteArrayBody(message.encode());
			
			HttpResult httpResult = httpClient.execute();
			if(httpResult.isSuccess()) {
				String tempBody = httpResult.getContent(message.getCharset().name);
				message.setResponse(tempBody);
				if (checkSuccessFlag(message.getMethodAlias(), tempBody)) {
					message.setPushStatus(PushStatus.SUCCESS);
				} else {
					message.setPushStatus(PushStatus.FAIL);
				}				
			} else {
				message.setPushStatus(PushStatus.FAIL);
				message.setResponse(StringUtils.substring(httpResult.toString(message.getCharset().name), 0, 200));
			}						
		} catch (Throwable t) {
			message.setPushStatus(PushStatus.EXCEPTION);
			message.setResponse(StringUtils.substring(t.getMessage(), 0, 100));			
			errorLogger.error(this.getServerAlias() + " send pushMessage error", t);
		} finally {		
			sendLogger.debug(String.format("serverAlias:%s, message:%s", this.getServerAlias(), JSON.toJSONString(message)));
		}
	}	
	
	@Override
	public void close() {		
		connection.close();
		super.close();
	}

	@Override	
	protected boolean isExpired(PushMessage message) {
		return repeatStrategyManager.isExpired(proxyMethodAlias, message);
	}
	@Override		
	protected boolean isPermitSend(PushMessage message) {
		return repeatStrategyManager.isPermitSend(proxyMethodAlias, message);
	}
	@Override		
	protected boolean checkSuccessFlag(String methodAlias, String value) {
		return repeatStrategyManager.checkSuccessFlag(proxyMethodAlias, value);
	}
	@Override		
	protected boolean isPermitRepeat(PushMessage message) {
		return repeatStrategyManager.isPermitRepeat(proxyMethodAlias, message);
	}
	
	@Override
	public void addConcurrentStrategy(ConcurrentStrategy strategy) {
		throw new IllegalArgumentException("in proxy mode, not permit add concurrentStrategy");
	}	
	@Override
	public void addRepeatStrategy(RepeatStrategy strategy) {
		throw new IllegalArgumentException("in proxy mode, not permit add repeatStrategy");
	}
}
